<template>
  <div class="padding_15">
    <el-form :model="classForm" label-width="120px" :disabled="disabled">
      <el-form-item label="父类" v-if="isShowParentNode">
        <el-cascader class="input_item" placeholder="请选择父类" v-model="classForm.parentNode" :options="newClassList" @change="changeNode" :props="{ children: 'goodsCategoryModelList', label: 'title', value: 'id', checkStrictly: true }" clearable :disabled="mode"></el-cascader>
      </el-form-item>
      <el-form-item label="分类名称" required>
        <el-input class="input_item" v-model="classForm.title" placeholder="请输入分类名称" @input="watchInput($event, 'title')" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="分类编码" v-if="newmode == true" required>
        <el-input class="input_item" v-model.trim="classForm.number" placeholder="请输入分类编码" :maxlength="classForm.level === 1 ? 1 : 2" @keyup="inputCode" @input="inputSuppCode" show-word-limit> </el-input>
        <span class="text-gray" v-if="classForm.level === 1">(请输入大写字母)</span>
        <span class="text-gray" v-else>(请输入数字或大写字母)</span>
      </el-form-item>
      <el-form-item label="分类编码" v-else required>
        <el-input class="input_item" v-model.trim="classForm.number" placeholder="请输入分类编码" :maxlength="length === 0 ? 1 : 2" @keyup="inputCode" @input="inputSuppCode" show-word-limit></el-input>
        <span class="text-gray" v-if="length === 0">(请输入大写字母)</span>
        <span class="text-gray" v-else>(请输入数字或大写字母)</span>
      </el-form-item>
      <el-form-item label="排序" required>
        <el-input class="input_item" v-model.trim="classForm.sort" placeholder="请输入4位之内纯数字" maxlength="4" show-word-limit @keydown.native="inputUnpass" @input="inputCodeNumber"></el-input>
      </el-form-item>      
      <template v-if="classForm.parentNode && classForm.parentNode.length">
        <el-form-item label="分类图片">
          <app-uploader title="分类图片" :limit="1" accept="image/*" :disabled="disabled" :file-size="0.2" :init-files="classForm.imgUrl ? [classForm.imgUrl] : []" :file-format="fileFormat" @change="handleImgOption"></app-uploader>
        </el-form-item>
        <el-form-item>
          <div class="text-gray">图片尺寸建议100*100正方形,最好为透明底的png图片，且大小不超过200KB</div>
        </el-form-item>
        <!-- <el-form-item label="启用状态">
          <el-radio-group v-model="classForm.status">{{classForm.status}}
            <el-radio :label="1" >启用</el-radio>
            <el-radio :label="0" >禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="尺码模板">
         <el-select v-model="classForm.sizeTemplateId" filterable placeholder="请选择" clearable>
          <el-option
            v-for="item in sizeOptions"
            :key="item.id"
            :label="item.title"
            :value="item.id">
          </el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="绑定属性">
          <el-table :data="classForm.tags" border max-height="480">
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column prop="propertyName" label="绑定属性" width="150"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div v-if="scope.row && scope.row.propertyId">
                  <el-button @click="unbundlingDialog(scope.row)">解绑</el-button>
                  <el-button @click="openAttrDialog(scope.$index)">修改</el-button>
                </div>
                <el-button v-else @click="openAttrDialog(scope.$index)">选择属性</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- <div class="el-input--medium flex flex-start">
            <div class="el-input__inner input_item flex align-center flex-wrap tags_box">
              <el-tag class="tag_item" v-for="(tag, index) in classForm.tags" :key="tag.propertyId" :closable="!disabled" type="info" @close="deleteTag(index)">{{ tag.propertyName }}</el-tag>
            </div>
            <el-button type="primary" @click="openAttrDialog()" style="height: 36px">选择属性</el-button>
          </div> -->
        </el-form-item>
        <el-form-item label="税率税码" v-if="classForm.level == 3">
          <template v-if="classForm.rateList && classForm.rateList.length > 0">
           <el-table class="margin_top_20" :data="classForm.rateList" border max-height="480" width="100%" size="medium">
            <el-table-column prop="title" label="分类名称" width="150"></el-table-column>
            <el-table-column prop="taxNumber" label="分类编码" width="200"></el-table-column>
            <el-table-column prop="shortNumber" label="分类简码" width="200">
              <template slot-scope="scope">
                <span v-if="scope.row.shortNumber">{{ scope.row.shortNumber }}</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="taxRate" label="税率" width="150">
              <template slot-scope="scope">
                <span>{{ Number(scope.row.taxRate) * 100 }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="abbreviation" label="简称" width="160"></el-table-column>
            <el-table-column prop="stated" label="说明" width="220"></el-table-column>
            <el-table-column prop="keywords" label="关键字" width="200"></el-table-column>
          </el-table>
          <el-row :gutter="10" class="text-center">
            <br/>
            <el-pagination background @size-change="handleRateChange" @current-change="handleRatePagingChange" :current-page="pageRateIndex" :page-sizes="pageRateSizes" :page-size="pageRateSize" :layout="paginationLayout" :total="pageRateCount"> </el-pagination>
          </el-row>
          </template>
          <div v-else>暂未选择税率税码</div>
      </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" @click="confirm()">确定</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-form v-if="roleBtns.includes('sys:fincial:update') || $store.getters.isAdmin" :model="finailForm" label-width="120px" :disabled="fincialdisabled">
      <el-form-item label="税率税码" >
          <el-button @click="chooseRate">选择税率税码</el-button>
          <template v-if="rateList && rateList.length > 0">
        <el-table class="margin_top_20" :data="rateList" border max-height="480" width="100%" size="medium">
            <el-table-column prop="title" label="分类名称" width="150"></el-table-column>
            <el-table-column prop="taxNumber" label="分类编码" width="200"></el-table-column>
            <el-table-column prop="taxRate" label="税率" width="150">
              <template slot-scope="scope">
                <span>{{ Number(scope.row.taxRate) * 100 }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="abbreviation" label="简称" width="160"></el-table-column>
            <el-table-column prop="stated" label="说明" width="220"></el-table-column>
            <el-table-column prop="keywords" label="关键字" width="200"></el-table-column>
          </el-table>
      </template>
      </el-form-item>
      <el-form-item>
      <el-button type="primary" @click="closeFincialDialog()" >确 定</el-button>
      </el-form-item>
    </el-form> -->
    <el-dialog title="绑定数据" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="isShowDialog">
      <el-row :gutter="10">
        <el-col :span="3">
          <el-radio-group v-model="checkRadio" class="margin_left_10">
            <el-radio-button :value="index + 1" :label="index + 1" v-for="(item, index) in checkedList" :key="'radio' + index"></el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="13">
          <!-- v-model="propertyName" -->
          <el-input placeholder="请输入属性名称" v-model="queryName" prefix-icon="el-icon-search" @keydown.native="searchAtt($event)" class="margin_bottom_10"></el-input>
          <el-table v-loading="loading" :data="pageData" row-key="id" ref="multipleTableRef" :header-cell-style="tableHeaderStyle" @select="handleOneItem">
            <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="checkSelectable" prop="index"></el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column property="propertyName" label="属性名称"></el-table-column>
            <el-table-column property="subtitle" label="属性描述"></el-table-column>
          </el-table>
          <br />
          <el-pagination class="text-center" background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes" :page-size="pageSize" :layout="paginationLayout" :total="pageCount"> </el-pagination>
        </el-col>
        <el-col :span="7">
          <el-table :data="checkedList" border max-height="480" highlight-current-row @row-click="handleCurrentChange">
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="propertyName" label="绑定属性">
              <template slot-scope="scope">{{scope.row ? scope.row.propertyName : ''}}</template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="closeAttrDialog()" >确 定</el-button> 
      </div>
    </el-dialog>
    <!-- 税率税码列表 -->
    <rate-list :visible.sync="isShowRateDialog" :selectedList="rateList" @selected="getSelectProperty"></rate-list>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Setting from '@/settings'
import AppUploader from '@/components/AppUploader/index';
import RateList from '@/views/store-management/components/rateList';
import { GetStoreAttrListByParams, GetFinicalDataList,GetFinicalBindList, GetSizeListCopy } from '@/views/store-management/services/index'

export default {
  components: {
    AppUploader,
    RateList
  },
  props: {
    mode: false,
    classList: null,
  },
  computed: {
    ...mapGetters(['roleBtns']),
    newmode() {
      return this.mode
    },
    newClassList() {
      return this.classList.map(child => {
        if (child.goodsCategoryModelList && child.goodsCategoryModelList.length) {
          child.goodsCategoryModelList = child.goodsCategoryModelList.map(childChild => {
            childChild.goodsCategoryModelList = null
            return childChild
          })
        }
        return child
      })
    },
    rateList() {
      if(this.finailForm.classId) {
       this.getBindFincial()
      }else {
        return []
      }
    }
  }, 
  data() {
    return {
      classForm: {
        parentNode: [],
        title: '',
        number: '',
        sort: '',
        imgUrl: '',
        tags: [null, null, null, null],
        level: '',
        rateList: [],
        sizeTemplateId: null,
        status: 1
      },
      finailForm: {
        classId: '',
        rateList: []
      },
      // rateList: [],
      isShowDialog: false,
      isShowRateDialog: false,
      loading: false,
      pageIndex: 1,
      pageData: [],
      pageCount: 0,
      pageSize: Setting.defaultTablePaginationSize,
      pageSizes: Setting.tablePaginationSizes,
      tableHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      pageRateCount: 0,
      pageRateIndex: 1,
      pageRateSize: Setting.defaultTablePaginationSize,
      pageRateSizes: Setting.tablePaginationSizes,
      tableRateHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      multipleSelection: [],
      checkedList: [null, null, null, null], //已选中的行
      isShowParentNode: true,
      disabled: false,
      fincialdisabled: false,
      staticList: [],
      sizeOptions: [], //尺码模板
      length: 0,
      attributeForm: [
        {
          sort: '1',
          propertyName: '',
          propertyId: '',
        },
        {
          sort: '2',
          propertyName: '',
          propertyId: '',
        },
        {
          sort: '3',
          propertyName: '',
          propertyId: '',
        },
        {
          sort: '4',
          propertyName: '',
          propertyId: '',
        },
      ],
      checkRadio: 1,
      status: 3,
      queryName: '',
      fileFormat: ['jpg', 'jpeg', 'png']
    }
  },
  methods: {
    // 选择税率税码
    chooseRate() {
      // this.getRateList() 
      this.isShowRateDialog = true
    },
    getSizeModules() {
      GetSizeListCopy({
        search: '',
        status: 1,
        // sort: true,
        // sortField: ''
      }).then(res => {
        console.log(res)
        if(res.code == 200) {
          this.sizeOptions = res.data
        }
      })
    },
    getBindFincial() {
       GetFinicalBindList({
        id: this.finailForm.classId,
        pageSize: this.pageRateSize,
        pageNum: this.pageRateIndex,
       }).then(res =>{
         console.log(res)
         if(res.code == 200 ) {
           this.classForm.rateList = res.data.list
           console.log(this.classForm.rateList)
           this.pageRateCount = res.data.total     
            if ((!res.data.list || !res.data.list.length) && this.pageRateIndex > 1) {
              this.pageRateIndex = 1
              this.getBindFincial()
            }
           }
       }).catch(error => {
         console.log(error)
          this.loading = false
        })

    },
    // 获取税率税码列表
    getRateList() {
      GetFinicalDataList({
        pageSize: this.pageSize,
        pageNum: this.pageIndex,
        title: this.search.title,
        taxNumber: this.search.taxNumber,
        abbreviation: this.search.abbreviation,
        keywords: this.search.keywords,
        status: this.search.status
      })
        .then(data => {
          if (data.code == 200) {
            this.pageData = data.data.list.map(item => {
              item.statusBoolean = !!item.status
              return item
            })
            this.pageRateCount = data.data.total

            if ((!data.data.list || !data.data.list.length) && this.pageIndex > 1) {
              this.pageRateIndex = 1
              this.getRateList()
            }
          }
          setTimeout(() => {
            // this.loading = false
          }, 300)
        })
        .catch(error => {
          // this.loading = false
        })
    },
    getSelectProperty(list) {
      console.log(list)
      this.rateList = list
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleImgOption(value) {
      if (value && value.length) {
        this.classForm.imgUrl = value[0].fileUrl;
      } else {
        this.classForm.imgUrl = '';
      }
    },
    searchAtt(e) {
      var keyCode = e.keyCode || e.which || e.charCode;
     if(keyCode=== 13) {
      this.getStoreAttrList()
     }
    },
    inputSuppCode(val) {
       if(this.newmode) {
           if(this.classForm.level === 1) {
           val=val.replace(/[^a-zA-Z]/g,'');
           this.classForm.number = val.toUpperCase();
           }else {
             val=val.replace(/[^\w\.\/]/ig,'');
           this.classForm.number = val.toUpperCase();
           }
       }else {
           if(this.length === 0) {
             val=val.replace(/[^a-zA-Z]/g,'');
             this.classForm.number = val.toUpperCase();
           }else {
             val=val.replace(/[^\w\.\/]/ig,'');
             this.classForm.number = val.toUpperCase();
           }
       }
     },
        inputCodeNumber(val) {
          val=val.replace(/\D/g,'');
          this.classForm.sort = val;
       },
       //  限制名称不能输入特殊字符
     watchInput(event, key) {
            this.classForm[key] = this.inputReplaceSpecialChar(event);
     },
    handleOneItem(selection, row) {
      if (!selection || !selection.length) {
        this.checkedList[this.checkRadio - 1] = null;
      } else {
        if (selection.includes(row)) {
          this.checkedList[this.checkRadio - 1] = {
            propertyId: row.id,
            propertyName: row.propertyName,
            propertyNo: row.propertyNo,
            sort: this.checkRadio,
            status: 1
          }
        } else {
          this.checkedList[this.checkRadio - 1] = null;
        }
      }
      this.$set(this.checkedList, this.checkRadio - 1, this.checkedList[this.checkRadio - 1]);
    },
    toggleRowSelection(rows, state) {
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i]
        this.$refs.multipleTableRef.toggleRowSelection(row, state)
      }
    },
    checkSelectable(row, index) {
       if (this.checkedList[this.checkRadio - 1]) {
        if (row.id == this.checkedList[this.checkRadio - 1].propertyId) {
          return 1;
        }
        return 0;
      } else {
        if (this.checkedList.find(item => item && item.propertyId== row.id)) {
          return 0;
        }
        return 1;
      }
    },
    handleCurrentChange(row, column, event) {
      this.checkRadio = event.target.parentNode.rowIndex + 1;
    },
    confirm() {
      this.$emit('submit')
    },
    closeFincialDialog() {
      this.$emit("submitFincial", this.rateList)
    },
    changeNode(event) {
      this.length = event.length
    },
    changeNodeLength() {
      this.length = this.classForm.parentNode.length;
    },
    // 选择属性值
    openAttrDialog(index) {
      this.checkedList = JSON.parse(JSON.stringify(this.classForm.tags));
      this.checkRadio = index + 1;
      this.isShowDialog = true;
      this.dialogDataSelect();
    },
    dialogDataSelect() {
      this.checkedList.forEach((item, index) => {
        if (item) {
          const finder = this.pageData.find(page => page.id == item.propertyId)
          if (finder) {
            this.$nextTick(() => {
              this.$refs.multipleTableRef.toggleRowSelection(finder, true);
            })
          }
        }
      })
    },
    unbundlingDialog(data) {
      this.$confirm('是否解绑该属性', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
             this.$set(this.classForm.tags, data.sort-1, null);
                done();
                  this.$message.success('解绑成功!');
            }else {
              done();
            }
          }
      }).then(() => {
            })
    },
    closeDialog() {
      this.isShowDialog = false
      this.$refs.multipleTableRef.clearSelection()
    },
    closeAttrDialog() {
      this.isShowDialog = false
      this.checkedList.forEach((item, index) => {
        this.classForm.tags[index] = item;
        this.$set(this.classForm.tags, index, item);
      });
      this.$refs.multipleTableRef.clearSelection()
    },
    // 移除属性值
    deleteTag(index) {
      this.classForm.tags.splice(index, 1)
    },
    // table组件选中事件
    handleSelectionChange(selectlist) {
      if (selectlist.length > 5) {
        //单选时为1，需要选择n项改数值为n就可以
        this.$refs.multipleTableRef.toggleRowSelection(selectlist[4], false) //超出指定选择个数后，把第一个选中的selection设为false
        selectlist.splice(0, 5) //同时要把选中第一项移除
      }
      this.multipleSelection = selectlist
    },
    // 分页事件
    handleSizeChange(event) {
      this.pageIndex = 1
      this.pageSize = event
      this.getStoreAttrList()
    },
    handlePagingChange(event) {
      this.pageIndex = event
      this.getStoreAttrList()
    },
     // 税率税码分页事件
    handleRateChange(event) {
      this.pageRateIndex = 1
      this.pageRateSize = event
      this.getBindFincial()
    },
    handleRatePagingChange(event) {
      this.pageRateIndex = event
      this.getBindFincial()
    },
    // 重置表单
    resetClassForm() {
      this.classForm = {
        parentNode: [],
        title: '',
        number: '',
        sort: '',
        imgUrl: '',
        tags: [null,null,null,null],
        level: '',
        rateList: [],
        sizeTemplateId: null,
        status: 1
      }
      this.multipleSelection = [];
    },
    // 获取属性值数据
    getStoreAttrList() {
      this.loading = true
      GetStoreAttrListByParams({
        status: 1,
        search: this.queryName,
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
      })
        .then(data => {
          this.loading = false
          if (data.code == 200) {
            this.pageData = data.data.list
            this.pageCount = data.data.total

            // 赋值勾选的数据
            if (this.pageData && this.pageData.length) {
              this.dialogDataSelect();
            }
          }
        })
        .catch(error => {
          this.loading = false
        })
    },
  },
  activated() {
    this.getSizeModules()
    this.getStoreAttrList()
  },
}
</script>

<style lang="scss" scoped>
.input_item {
  width: 40%;
  min-width: 320px;
}

.tags_box {
  min-height: 36px;
  height: auto;
  margin-left: -2px;
  margin-right: -2px;

  .tag_item {
    margin: 2px;
  }
}
::v-deep .el-radio-button__inner{
  border-left-width: 1px;
  border-left-style: solid;
  border-left-color:#DCDFE6;
}
::v-deep .el-dialog__body {
  border-top: 1px solid rgba(0,0,0,0.35);;
}
::v-deep .el-radio-button .el-radio-button__inner {
    border-radius: 4px 4px 4px 0;
}
::v-deep .el-table th > .cell:nth-child(1) .el-checkbox {
  display: none;
}
</style>
